// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/2/21 16:06
// 文件名称 ：   handlers.go
// 工程名称 ：   videostream
// 开发工具 ：   GoLand
//

package main

import (
	"encoding/json"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"io/ioutil"
	"johnsonsmile.com/videostream/api/dbops"
	"johnsonsmile.com/videostream/api/defs"
	"johnsonsmile.com/videostream/api/session"
	"johnsonsmile.com/videostream/api/utils"
	"log"
	"net/http"
)

// 用户注册的
func Register(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {

	// 设置为json
	writer.Header().Set("Content-type", "application/json")

	res, _ := ioutil.ReadAll(request.Body)
	ubody := &defs.UserCredential{}
	if err := json.Unmarshal(res, ubody); err != nil {
		sendErrorResponse(writer, defs.ErrorRequestBodyParseFailed)
		return
	}

	if err := dbops.AddUserCredential(ubody.Username, ubody.Pwd); err != nil {
		sendErrorResponse(writer, defs.ErrorDBError)
		return
	}

	id := session.GenerateNewSessionId(ubody.Username)
	su := &defs.SignedUp{
		Success:   true,
		SessionId: id,
	}
	bytes, err := json.Marshal(su)
	if err != nil {
		sendErrorResponse(writer, defs.ErrorInternalServerError)
		return
	}
	sendNormalResponse(writer, string(bytes), http.StatusCreated)
}

// 用户登录
func Login(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {

	// 设置为json
	writer.Header().Set("Content-type", "application/json")

	// 获取参数
	res, _ := ioutil.ReadAll(request.Body)
	ubody := &defs.UserCredential{}
	if err := json.Unmarshal(res, ubody); err != nil {
		sendErrorResponse(writer, defs.ErrorRequestBodyParseFailed)
		return
	}
	fmt.Println(ubody.Username, ubody.Pwd)

	username := params.ByName("username")

	pwd, err := dbops.GetUserCredential(username)
	if err != nil || len(pwd) == 0 || pwd != ubody.Pwd {
		sendErrorResponse(writer, defs.ErrorUserNotAuthed)
		return
	}

	id := session.GenerateNewSessionId(username)
	si := &defs.SignedIn{Success: true, SessionId: id}
	if resp, err := json.Marshal(si); err != nil {
		sendErrorResponse(writer, defs.ErrorInternalServerError)
	} else {
		sendNormalResponse(writer, string(resp), http.StatusOK)
	}
}

// 获取用户信息
func GetUserInfo(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if !ValidateUser(w, r) {
		return
	}
	uname := p.ByName("username")
	u, err := dbops.GetUser(uname)
	if err != nil {
		sendErrorResponse(w, defs.ErrorDBError)
		return
	}

	ui := &defs.UserInfo{Id: u.Id}
	if resp, err := json.Marshal(ui); err != nil {
		sendErrorResponse(w, defs.ErrorInternalServerError)
	} else {
		sendNormalResponse(w, string(resp), 200)
	}

}

// 添加视频
func AddNewVideo(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if !ValidateUser(w, r) {
		log.Printf("Unathorized user \n")
		return
	}

	res, _ := ioutil.ReadAll(r.Body)
	nvbody := &defs.NewVideo{}
	if err := json.Unmarshal(res, nvbody); err != nil {
		log.Printf("%s", err)
		sendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return
	}

	vi, err := dbops.AddNewVideo(nvbody.AuthorId, nvbody.Name)
	log.Printf("Author id : %d, name: %s \n", nvbody.AuthorId, nvbody.Name)
	if err != nil {
		log.Printf("Error in AddNewVideo: %s", err)
		sendErrorResponse(w, defs.ErrorDBError)
		return
	}

	if resp, err := json.Marshal(vi); err != nil {
		sendErrorResponse(w, defs.ErrorInternalServerError)
	} else {
		sendNormalResponse(w, string(resp), http.StatusCreated)
	}
}

// 获取所有视频的列表
func ListAllVideos(w http.ResponseWriter, r *http.Request, p httprouter.Params) {

	if !ValidateUser(w, r) {
		return
	}

	uname := p.ByName("username")
	vs, err := dbops.ListVideoInfo(uname, 0, utils.GetCurrentTimestampSec())
	if err != nil {
		log.Printf("Error in ListAllvideos: %s", err)
		sendErrorResponse(w, defs.ErrorDBError)
		return
	}

	vsi := &defs.VideosInfo{Videos: vs}
	if resp, err := json.Marshal(vsi); err != nil {
		sendErrorResponse(w, defs.ErrorInternalServerError)
	} else {
		sendNormalResponse(w, string(resp), http.StatusOK)
	}
}

// 删除视频
func DeleteVideo(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if !ValidateUser(w, r) {
		return
	}
	vid := p.ByName("vid")
	err := dbops.DeleteVideoInfo(vid)
	if err != nil {
		log.Printf("Error in DeletVideo: %s", err)
		sendErrorResponse(w, defs.ErrorDBError)
		return
	}

	// TODO: 删除视频文件
	go utils.SendDeleteVideoRequest(vid)
	sendNormalResponse(w, "", http.StatusNoContent)
}

// 添加评论
func PostComment(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if !ValidateUser(w, r) {
		return
	}

	reqBody, _ := ioutil.ReadAll(r.Body)

	cbody := &defs.NewComment{}
	if err := json.Unmarshal(reqBody, cbody); err != nil {
		log.Printf("%s", err)
		sendErrorResponse(w, defs.ErrorRequestBodyParseFailed)
		return
	}

	vid := p.ByName("vid")
	if err := dbops.AddNewComments(vid, cbody.AuthorId, cbody.Content); err != nil {
		log.Printf("Error in PostComment: %s", err)
		sendErrorResponse(w, defs.ErrorDBError)
	} else {
		sendNormalResponse(w, "ok", http.StatusCreated)
	}
}

func ShowComments(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if !ValidateUser(w, r) {
		return
	}

	vid := p.ByName("vid")
	cm, err := dbops.ListComments(vid, 0, utils.GetCurrentTimestampSec())
	if err != nil {
		log.Printf("Error in ShowComments: %s", err)
		sendErrorResponse(w, defs.ErrorDBError)
		return
	}

	cms := &defs.Comments{Comments: cm}
	if resp, err := json.Marshal(cms); err != nil {
		sendErrorResponse(w, defs.ErrorInternalServerError)
	} else {
		sendNormalResponse(w, string(resp), http.StatusOK)
	}
}
